#include "modifymyselfdialog.h"
#include "ui_modifymyselfdialog.h"
#include "util.h"
#include "newpassworddialog.h"
#include "model/datacenter.h"

ModifyMyselfDialog::ModifyMyselfDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ModifyMyselfDialog)
{
    ui->setupUi(this);
    ui->passwordWidget->hide();

    this->setWindowFlag(Qt::FramelessWindowHint);

    // 加载用户手机号 和 昵称 到界面
    auto dataCenter = model::DataCenter::getInstance();
    auto myselfInfo = dataCenter->getMyselfInfo();
    ui->phoneNumberLabel->setText(hidePhoneNumber(myselfInfo->photoNum));
    ui->nickNameEdit->setText(myselfInfo->nickname);

    connect(ui->submitBtn, &QPushButton::clicked, this, &ModifyMyselfDialog::onSubmitBtnClicked);
    connect(ui->cancelBtn, &QPushButton::clicked, this, &ModifyMyselfDialog::onCancelBtnClicked);
    connect(ui->passwordBtn, &QPushButton::clicked, this, &ModifyMyselfDialog::showPasswordDlg);
    connect(ui->changePasswordBtn, &QPushButton::clicked, this, &ModifyMyselfDialog::showPasswordDlg);
}

ModifyMyselfDialog::~ModifyMyselfDialog()
{
    delete ui;
}

void ModifyMyselfDialog::onSubmitBtnClicked()
{
    auto dataCenter = model::DataCenter::getInstance();
    auto myselfInfo = dataCenter->getMyselfInfo();
    // 修改密码
    if(!newPassword.isEmpty()) {
        dataCenter->setPasswordAsync(newPassword);
    }

    // 修改昵称
    // trimmed: 去除字符串起始和节数的空白字符
    const QString nickName = ui->nickNameEdit->text().trimmed();
    if(nickName != myselfInfo->nickname) {
        dataCenter->setNicknameAsync(nickName);
    }

    // 关闭对话框
    this->close();
}

void ModifyMyselfDialog::onCancelBtnClicked()
{
    this->close();
}

void ModifyMyselfDialog::showPasswordDlg()
{
    NewPasswordDialog* dialog = new NewPasswordDialog();
    dialog->exec();
    QString currentPassword = dialog->getPassword();
    if(currentPassword.isEmpty()) {
        LOG() << "取消修改密码";
        return ;
    }
    newPassword = currentPassword;

    // 隐藏修改密码按钮, 显⽰已修改
    ui->passwordBtn->hide();
    ui->passwordWidget->show();

    delete dialog;
}
